import { createSlice } from "@reduxjs/toolkit";
import { RootState } from "../index.ts";

interface ProductState {
  warehouse: IWarehouse[];
  category: ICategory[];
}

export interface IWarehouse {
  id: number;
  wName: string;
  address: string;
  note: string;
  createTime: string;
}

export interface ICategory {
  id: number;
  cName: string;
  note: string;
  createTime: string;
}

const initialState: ProductState = {
  warehouse: [
    {
      id: 1,
      wName: "新疆仓",
      address: "新疆维吾尔自治区巴音郭楞自治州若羌县",
      note: "备用仓",
      createTime: "2025-4-23",
    },
    {
      id: 2,
      wName: "浙江仓",
      address: "浙江省杭州市西湖",
      note: "",
      createTime: "2023-4-20",
    },
    {
      id: 3,
      wName: "浙江丽水仓",
      address: "浙江省杭州市西湖",
      note: "用于存放数码产品",
      createTime: "2023-4-20",
    },
    {
      id: 4,
      wName: "重庆仓",
      address: "重庆市渝北区",
      note: "用于存放海鲜产品",
      createTime: "2023-4-20",
    },
  ],
  category: [
    { id: 1, cName: "数码产品", note: "数码", createTime: "2025-4-23" },
    { id: 2, cName: "男装", note: "", createTime: "2025-4-23" },
    { id: 3, cName: "箱包", note: "", createTime: "2025-4-23" },
    { id: 4, cName: "家用电器", note: "", createTime: "2025-4-23" },
  ],
};

const productsSlice = createSlice({
  name: "products",
  initialState,
  reducers: {
    addWarehouse: (state, action) => {
      state.warehouse.push(action.payload);
    },
    updateWarehouse: (state, action) => {
      const { id, wName, address, note } = action.payload;

      const warehouse = state.warehouse.find((w) => w.id === id);

      if (warehouse) {
        warehouse.wName = wName;
        warehouse.address = address;
        warehouse.note = note;
      }
    },
    deleteWarehouse: (state, action) => {
      const { id } = action.payload;
      state.warehouse = state.warehouse.filter((w) => w.id !== id);
    },
    addCategory: (state, action) => {
      state.category.push(action.payload);
    },
    updateCategory: (state, action) => {
      const { id, cName, note } = action.payload;
      const c = state.category.find((w) => w.id === id);
      if (c) {
        c.cName = cName;
        c.note = note;
      }
    },
    deleteCategory: (state, action) => {
      const { id } = action.payload;
      state.category = state.category.filter((w) => w.id !== id);
    },
  },
});

export const {
  addWarehouse,
  updateWarehouse,
  deleteWarehouse,
  addCategory,
  updateCategory,
  deleteCategory,
} = productsSlice.actions;

export default productsSlice.reducer;

export const selectAllWarehouse = (state: RootState) =>
  state.products.warehouse;

export const selectAllCategory = (state: RootState) => state.products.category;
